package com.qiantu.phone.ui.fragment.device;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppFragment;
import com.qiantu.phone.event.DeviceDetailChangeEvent;
import com.qiantu.phone.event.DeviceKeyChangeEvent;
import com.qiantu.phone.event.DeviceLocalChangeEvent;
import com.qiantu.phone.event.GroupDissolutionEvent;
import com.qiantu.phone.ui.activity.ControllerDeviceAcitvity;
import com.qiantu.phone.ui.activity.DeviceSettingActivity;
import com.qiantu.phone.ui.activity.HomeActivity;
import com.qiantu.phone.ui.activity.KGXControllerDeviceAcitvity;
import com.qiantu.phone.ui.activity.RoomDeviceActivity;
import com.qiantu.phone.ui.fragment.HomeFragment;
import com.qiantu.phone.ui.fragment.HomeNewFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public abstract class BaseDeviceFragment extends AppFragment<AppActivity> {

    public static final String STATUS = "status";

    protected TextView tvDeviceName;
    protected TextView tvFloorRoom;
    protected ImageView btnSetting;
    protected DeviceBean mDevice;
    //1有设置按钮 2没有设置按钮
    private int enterType;

    protected abstract int getLayoutId();

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        View contentView = findViewById(R.id.content_view);
        tvDeviceName = findViewById(R.id.tv_device_name);
        tvFloorRoom = findViewById(R.id.tv_floor_room);
        btnSetting = findViewById(R.id.btn_setting);
        contentView.setOnClickListener(mOnClickListener);
        if(AppApplication.getInstance().getCurHouseInfo().getRoleType() != 2){
            if(enterType == 1){
                btnSetting.setVisibility(View.VISIBLE);
                btnSetting.setOnClickListener(mOnClickListener);
            }else{
                btnSetting.setVisibility(View.GONE);
            }
        }else{
            btnSetting.setVisibility(View.GONE);
        }

    }

    public void setEnterType(int enterType){
        this.enterType = enterType;
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if(savedInstanceState != null){
            String deviceSerialNo = savedInstanceState.getString("deviceSerialNo");
            mDevice = LLDeviceDBManager.getInstance(getContext()).get(deviceSerialNo);
        }
        super.onCreate(savedInstanceState);
    }

    public void setDevice(String deviceSerialNo){
        mDevice = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(deviceSerialNo);
    }

    /**
     *
     *  新加的设备指令 在 deviceEquals 方法里注意添加
     */
    private void needUpdateView(DeviceBean newDevice){
        //设备状态跟当前一样就不刷新了
        if(mDevice.getDeviceType().equals(newDevice.getDeviceType())
                && mDevice.getIsOnline() == newDevice.getIsOnline()
                && mDevice.getName().equals(newDevice.getName())
                && mDevice.getRoomSerialNo().equals(newDevice.getRoomSerialNo())
                && mDevice.getStateData().getStatus().deviceEquals(newDevice.getStateData().getStatus())){
            return;
        }
        if (mDevice.getType().equals("wireless_433") || mDevice.getType().equals("wireless_315") || mDevice.getType().equals("infrared")){
            return;
        }
        mDevice = newDevice;
        updateView();
    }

    protected void updateView(){
        updateTitleView();
    }

    private void updateTitleView(){
        tvDeviceName.setText(mDevice.getName());
//        if(mDevice.isIsOnline()){
//            tvDeviceName.setAlpha(1f);
//        }else{
//            tvDeviceName.setAlpha(0.6f);
//        }
        if(mDevice.getLinkType() == 3){
            tvFloorRoom.setText(mDevice.getFloorName());
        }else {
            tvFloorRoom.setText(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(mDevice.getRoomSerialNo()));
        }
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.content_view:
                    if (getAttachActivity() instanceof HomeActivity) {
                        ((HomeActivity) getAttachActivity()).hideDeviceView();
                    }else if(getAttachActivity() instanceof DeviceSettingActivity){
                        ((DeviceSettingActivity) getAttachActivity()).hideDeviceView();
                    }else if(getAttachActivity() instanceof ControllerDeviceAcitvity){
                        ((ControllerDeviceAcitvity) getAttachActivity()).hideDeviceView();
                    }else if(getAttachActivity() instanceof RoomDeviceActivity){
                        ((RoomDeviceActivity) getAttachActivity()).hideDeviceView();
                    }else if(getAttachActivity() instanceof KGXControllerDeviceAcitvity){
                        ((KGXControllerDeviceAcitvity) getAttachActivity()).hideDeviceView();
                    }
                    break;
                case R.id.btn_setting:
                    DeviceSettingActivity.start(getContext(), mDevice.getDeviceSerialNo(), true);
                    break;
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceDetailChangeEvent(DeviceDetailChangeEvent event) {
        //设备状态推送
        if (mDevice.getDeviceSerialNo().equals(event.deviceSerialNo)) {
            DeviceBean newDevice = LLDeviceDBManager.getInstance(getContext()).get(mDevice.getDeviceSerialNo());
            if(newDevice == null || newDevice.getIsDisable()){
                if (getActivity() != null) {
                    hideDeviceFragment(this);
                }
            }else {
                if (getActivity() != null) {
                    if (getActivity() instanceof HomeActivity) {
//                        HomeNewFragment homeFragment = ((HomeActivity)getActivity()).getHomeFragment();
                        boolean currentIsFavourite = false;
                        //设备详情设备变成首页不显示了或者当前页面是常用，但是当前设备详情设备变成非常用了就隐藏设备详情
                        if (!newDevice.getIsHomePage() || (currentIsFavourite && !newDevice.getIsFavourite())) {
                            hideDeviceFragment(this);
                        } else {//设备是首页显示就更新view,否则就隐藏当前的设备弹框
                            needUpdateView(newDevice);
                        }
                    } else {
                        needUpdateView(newDevice);
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceKeyChangeEvent(DeviceKeyChangeEvent event) {
        //设备状态推送
        if (mDevice.getDeviceSerialNo().equals(event.deviceSerialNo)) {
            mDevice = LLDeviceDBManager.getInstance(getContext()).get(mDevice.getDeviceSerialNo());
            if(mDevice == null || mDevice.getIsDisable()){
                if (getActivity() != null) {
                    hideDeviceFragment(this);
                }
            }else {
                if (getActivity() != null) {
                    if (getActivity() instanceof HomeActivity) {
                        if (!mDevice.getIsHomePage()) {
                            hideDeviceFragment(this);
                        } else {//设备是首页显示就更新view,否则就隐藏当前的设备弹框
                            updateView();
                        }
                    } else {
                        updateView();
                    }
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void groupDissolutionEvent(GroupDissolutionEvent event){
        if (mDevice.getDeviceSerialNo().equals(event.deviceSerialNo)) {
            hideDeviceFragment(this);
        }
    }

    protected void refreshDeviceStateByLocal(){
        //本地先刷新设备状态
        EventBus.getDefault().post(new DeviceLocalChangeEvent(mDevice.getRoomSerialNo(), mDevice.getDeviceSerialNo(), mDevice.getIsFavourite()));
        EventBus.getDefault().post(new DeviceLocalChangeEvent(mDevice.getFloorSerialNo(), mDevice.getDeviceSerialNo(), mDevice.getIsFavourite()));
    }

    private FragmentManager mFragmentManager;
    private void hideDeviceFragment(BaseDeviceFragment fragment){
        if (mFragmentManager == null) {
            mFragmentManager = getActivity().getSupportFragmentManager();
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (fragment != null && fragment.isAdded()) {
            transaction.remove(fragment);
        }
        // 事务提交
        transaction.commitNowAllowingStateLoss();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if(mDevice != null){
            outState.putString("deviceSerialNo", mDevice.getDeviceSerialNo());
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
